#!/usr/bin/env python3
"""
同步MySQL内容到Elasticsearch
"""

from models import SessionLocal, Content, ContentTag, ContentMedia, User, Tag
from services.es_client import ESClient
from datetime import datetime
import asyncio

async def sync_all_to_es():
    """同步所有已发布内容到ES"""
    db = SessionLocal()
    es_client = ESClient(use_async=False)
    
    try:
        # 获取所有已发布的内容
        contents = db.query(Content).filter(Content.status == 2).all()
        
        print(f"找到 {len(contents)} 条已发布内容")
        
        for content in contents:
            try:
                # 获取标签
                content_tags = db.query(ContentTag).filter(
                    ContentTag.content_id == content.id
                ).all()
                tag_ids = [ct.tag_id for ct in content_tags]
                
                if not tag_ids:
                    print(f"⚠️  内容 {content.id} 没有标签，跳过")
                    continue
                
                # 获取标签名称
                tags = db.query(Tag).filter(Tag.id.in_(tag_ids)).all()
                tag_names = [t.name for t in tags]
                
                # 获取首图
                first_media = db.query(ContentMedia).filter(
                    ContentMedia.content_id == content.id
                ).order_by(ContentMedia.sort_order).first()
                
                # 获取作者
                author = db.query(User).filter(User.id == content.author_id).first()
                
                # 构建ES文档
                es_doc = {
                    "content_id": content.id,
                    "title": content.title,
                    "description": content.description or "",
                    "author_id": content.author_id,
                    "author_nickname": author.nickname if author else "未知",
                    "tag_ids": tag_ids,
                    "tag_names": tag_names,
                    "status": content.status,
                    "view_count": content.view_count,
                    "like_count": content.like_count,
                    "comment_count": content.comment_count,
                    "share_count": content.share_count,
                    "collect_count": content.collect_count,
                    "first_image_url": first_media.media_url if first_media else None,
                    "media_urls": [first_media.media_url] if first_media else [],
                    "media_types": [first_media.media_type] if first_media else [],
                    "is_top": content.is_top,
                    "created_at": content.created_at.isoformat() if content.created_at else None,
                    "published_at": content.published_at.isoformat() if content.published_at else None
                }
                
        # 同步到ES
        result = await es_client.create_document(content.id, es_doc)
        print(f"[OK] 已同步内容 {content.id}: {content.title}")
        
    except Exception as e:
        print(f"[FAIL] 同步内容 {content.id} 失败: {e}")
        continue
        
        print(f"\n[OK] 同步完成！共处理 {len(contents)} 条内容")
        
    except Exception as e:
        print(f"[FAIL] 同步失败: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    asyncio.run(sync_all_to_es())

